import { login } from "src/api/login";
import { routes } from "src/router/routes";
import { fetchOwnerInfo } from "src/api/personAdmini";
import { gainMenuList, gainPerPage } from "src/api/permission";
import { weChatLogin } from "src/api/login.js";
import jwt_decode from "jwt-decode";

export function filterAsyncRoutes(detailRoute, route) {
  const res = [];
  route.forEach((item) => {
    if (item && item.meta) {
      // if (detailRoute.find(ele => ele.name === item.meta.fixedMenu)) {
      //     res.push(item)
      //     if (item.children && item.children.length > 0) {
      //         item.children = filterAsyncRoutes(detailRoute, item.children)
      //     }
      // } else if (detailRoute.find(ele => ele.url === item.path)) {
      //     res.push(item)
      // }
      res.push(item);
    }
  });
  return res;
}

const state = {
  token: localStorage.getItem("token_key_GFYW"),
  roles: [], // 当前需要展示的路由
  user: "",
  uid: "",
  db: "",
  personNameArr: [],
  routersArr: JSON.parse(localStorage.getItem("superRouters_GFYW")), // 显示在菜单栏的路由
  isSuper: {}, // 是否是员工和超级管理员,
};

const mutations = {
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_TOKEN: (state, token) => {
    // some() 数组方法：只要数组中有一个符合条件的，返回true。和every() 功能相反
    state.token = token;
  },
  SET_USERNAME: (state, user) => {
    state.user = user;
  },
  SET_UID: (state, uid) => {
    state.uid = uid;
  },
  SET_DB: (state, db) => {
    state.db = db;
  },
  SET_PERSON_NAME_ARR: (state, personNameArr) => {
    state.personNameArr = personNameArr;
  },
  SET_ROUTERS_ARR: (state, querys) => {
    const { data, query } = querys;
    if (query.is_staff && query.is_superuser) {
      state.routersArr = JSON.parse(
        localStorage.getItem("superRouters_GFYW")
      );
    } else {
      let _routes = JSON.parse(localStorage.getItem("superRouters_GFYW"));
      state.routersArr = filterAsyncRoutes(data, _routes);
    }
    localStorage.setItem(
      "routers_arr_GFYW",
      JSON.stringify(state.routersArr)
    );
  },
  SET_IS_SUPER: (state, isSuper) => {
    state.isSuper = isSuper;
  },
};

const actions = {
  loginFun({ commit, dispatch }, userInfo) {
    if (userInfo.hasOwnProperty("company_code")) {
      const { company_code, username, password } = userInfo;
      return new Promise((resolve, reject) => {
        login({
          company_code: company_code,
          usr: username.trim(),
          pwd: password,
        })
          .then((response) => {
            const { data, status, token, db, company } = response;
            console.log(response, "-------------- response ------------");
            if (status === 200) {
              const jwtDe = jwt_decode(token);
              commit("SET_TOKEN", token);
              commit("SET_USERNAME", data.username);
              commit("SET_UID", data.uid);
              commit("SET_DB", db);
              commit("SET_IS_SUPER", {
                is_staff: data.is_staff,
                is_superuser: data.is_superuser,
              });
              localStorage.setItem("exp_GFYW", jwtDe.exp);
              localStorage.setItem("token_key_GFYW", token);
              localStorage.setItem("username_GFYW", data.username);
              localStorage.setItem("user_id_GFYW", data.uid);
              localStorage.setItem("db_GFYW", db);
              localStorage.setItem("company_code2_GFYW", company_code);
              localStorage.setItem("gsName_GFYW", company.name);
              localStorage.setItem("titleName_GFYW", data.roles);
            }
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    } else {
      const { username, password } = userInfo;
      return new Promise((resolve, reject) => {
        login({ usr: username.trim(), pwd: password })
          .then((response) => {
            const { data, status, token, db, company } = response;
            console.log(response, "-------------- response ------------");
            if (status === 200) {
              const jwtDe = jwt_decode(token);
              commit("SET_TOKEN", token);
              commit("SET_USERNAME", data.username);
              commit("SET_UID", data.uid);
              commit("SET_DB", db);
              commit("SET_IS_SUPER", {
                is_staff: data.is_staff,
                is_superuser: data.is_superuser,
              });
              localStorage.setItem("exp_GFYW", jwtDe.exp);
              localStorage.setItem("token_key_GFYW", token);
              localStorage.setItem("username_GFYW", data.username);
              localStorage.setItem("user_id_GFYW", data.uid);
              localStorage.setItem("db_GFYW", db);
              localStorage.setItem("gsName_GFYW", company.name);
              localStorage.setItem("titleName_GFYW", data.roles);
            }
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    }
  },
  // 微信跳转登录
  weChatloginFun({ commit, dispatch }, item) {
    let str = {
      uid: item.uid,
      token: item.token,
    };
    return new Promise((resolve, reject) => {
      weChatLogin(str)
        .then((response) => {
          const { data, status, token, db, company } = response;
          if (status == 200 && data.status != 400) {
            const jwtDe = jwt_decode(token);
            commit("SET_TOKEN", token);
            commit("SET_USERNAME", data.username);
            commit("SET_UID", data.uid);
            commit("SET_DB", db);
            commit("SET_IS_SUPER", {
              is_staff: data.is_staff,
              is_superuser: data.is_superuser,
            });
            localStorage.setItem("exp_GFYW", jwtDe.exp);
            localStorage.setItem("token_key_GFYW", token);
            localStorage.setItem("username_GFYW", data.username);
            localStorage.setItem("user_id_GFYW", data.uid);
            localStorage.setItem("db_GFYW", db);
            localStorage.setItem("gsName_GFYW", company.name);
            localStorage.setItem("titleName_GFYW", data.roles);
            localStorage.setItem("euworkShop_wechatPathTo", item.returnurl);
            localStorage.setItem("euworkShop_wechatPathTo_path", true);
          } else {
            localStorage.setItem("euworkShop_wechatPathTo", item.returnurl);
            this.$router.push("login");
          }
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  /**
   * 退出登录
   */
  logoutFun({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      localStorage.removeItem("user_id_GFYW");
      localStorage.removeItem("exp_GFYW");
      localStorage.removeItem("username_GFYW");
      localStorage.removeItem("superRouters_GFYW");
      localStorage.removeItem("gsName_GFYW");
      localStorage.removeItem("titleName_GFYW");
      localStorage.removeItem("db_GFYW");
      localStorage.removeItem("routers_arr_GFYW");
      localStorage.removeItem("euworkShop_wechatPathTo");
      localStorage.removeItem("euworkShop_wechatPathTo_path");
      localStorage.removeItem("euWorkShop_boardViewRouterArr");
      localStorage.removeItem("euworkShop_goViewColor");
      if (state.token) {
        commit("SET_TOKEN", "");
        commit("SET_ROLES", []);
        localStorage.removeItem("token_key_GFYW");
      }
      resolve();
    });
  },
  // 获取全部的人员信息
  getAllPeraonInfo({ commit }) {
    return new Promise((resolve, reject) => {
      fetchOwnerInfo()
        .then((res) => {
          const { data } = res;
          commit("SET_PERSON_NAME_ARR", data);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  // 获取可访问的菜单列表
  getVisitMenu({ commit }, query) {
    return new Promise((resolve, reject) => {
      gainMenuList()
        .then((res) => {
          const { data } = res;
          commit("SET_ROUTERS_ARR", { data, query });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  // 判断跳转到的页面有没有权限
  getPagePremission({ commit, dispatch }, query) {
    return new Promise((resolve, reject) => {
      gainPerPage(query)
        .then((res) => {
          const { status, data } = res;
          if (status === 200) {
            if (query.page_url === "/assetHealth") {
              resolve({ permissions: false });
            } else {
              resolve(data);
            }
            resolve({ permissions: true });
            resolve(data);
          } else {
            resolve();
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
